package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 攻略主题接口实现类
 */
@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private MongoTemplate template;
    
    @Autowired
    private  IStrategyThemeService strategyThemeService;



    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemeRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        return strategyThemeRepository.findAll();
    }
    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {

        //查询对象
        Query query = new Query();
        //查询总数
        long totalCount = template.count(query, StrategyTheme.class);
        if (totalCount==0){
            return Page.empty();
        }
        Pageable pageable =PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(),Sort.Direction.ASC,"_id");
        query.with(pageable);
        List<StrategyTheme> list = template.find(query, StrategyTheme.class);

        return new PageImpl<>(list,pageable,totalCount);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {


        //判断是否带id
        if (StringUtils.hasLength(strategyTheme.getId())){
            //有则编辑
            this.update(strategyTheme);
        }else {
            //无则添加
            this.save(strategyTheme);
        }
    }
}
